package com.cxhc.app.api;

import com.cxhc.common.annotation.Anonymous;
import com.cxhc.common.core.domain.R;
import com.cxhc.common.utils.NanoIdUtils;
import com.cxhc.common.utils.QiniuUtils;
import com.cxhc.common.utils.file.FileUploadUtils;
import com.cxhc.common.utils.file.FileUtils;
import com.google.common.collect.ImmutableMap;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;


/**
 * 首页模块接口
 */
@RestController()
@RequestMapping("/api/upload")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ApiUpload{

    @Resource
    private QiniuUtils qiniuUtils;


    /**
     * 单个上传请求（需授权）
     */
    @Anonymous
    @SneakyThrows
    @PostMapping("/authFile")
    public R<Map<String, String>> qiNiuUploadFile(MultipartFile file) {
        String key = NanoIdUtils.randomNanoId(10);
        String url = qiniuUtils.scyGet(file, key);
        return R.ok(ImmutableMap.of("url", url, "fileName", key));
    }


    /**
     * 单个上传请求（需授权）
     */
    @Anonymous
    @SneakyThrows
    @PostMapping("/minioFile")
    public R<Map<String, String>> minioFile(@RequestParam("file") MultipartFile file) {
        Map<String, String> data = FileUploadUtils.uploadMinioMap(file);
        String url = data.get("url");
        String name = data.get("name");
        return R.ok(ImmutableMap.of(
                "url", data.get("url"),
                "fileName", FileUtils.getName(url),
                "saveUrl", name,
                "originalFilename", Objects.requireNonNull(file.getOriginalFilename())));
    }

    /**
     * 单个上传请求（需授权）
     */
    @Anonymous
    @SneakyThrows
    @RequestMapping("/minioDownloadFile")
    public ResponseEntity<byte[]> minioDownloadFile(String fileUrl,String orgName) {
        return FileUploadUtils.downloadMinioFile(fileUrl,orgName);
    }

    /**
     * 单个上传请求（需授权）
     */
    @Anonymous
    @SneakyThrows
    @RequestMapping("/minioPreviewFile")
    public ResponseEntity<byte[]> minioPreviewFile(String fileUrl,String orgName) {
        return FileUploadUtils.previewMinioFile(fileUrl,orgName);
    }

    /**
     * 单个上传请求（需授权）
     */
    @Anonymous
    @SneakyThrows
    @PostMapping("/minioRemoveFile")
    public R<String> minioRemoveFile(String fileName) {
        FileUploadUtils.minioRemoveFile(fileName);
        return R.ok();
    }

}
